<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.6.8/angular.min.js"></script>
  </head>
  <body>
    <div ng-app="myApp" ng-controller="myCtrl">
      <h1>{{indexName}}</h1>
      <!-- 自定义组件 -->
      <hello></hello>
    </div>

    <script>
        var app = angular.module("myApp", []);
        app.controller("myCtrl", function ($scope,) {
          $scope.indexName = "主页";
        });
        // 第一个组件，父组件
        app.component("hello", {
          template: `
              <div>
                  <h3>Hello</h3>
                  <world1></world1>
                  <world2></world2>
              </div>
          `,
          controller: function ($scope,EventService) {
            this.$onInit = function () {};
            EventService.on("send_msg",function(data){
              console.log("hello_receive",data);
            })
          },
        });
        // 第二个组件，子组件
        app.component("world1", {
          template: `
              <div>
                  <h4>World1</h4>
                  <button ng-click="$ctrl.submit()">发送数据</button>
              </div>
          `,
          controller: function ($scope,EventService) {
            this.$onInit = function () {};
            this.submit = function(){
              EventService.send("send_msg","world1_msg")
            }
          },
        });
        // 第三个组件，为兄弟组件
        app.component("world2", {
          template: `
              <div>
                  <h4>World2</h4>
              </div>
          `,
          controller: function ($scope,EventService) {
            this.$onInit = function () {};
            EventService.on("send_msg",function (data) {
              console.log("world2_receive",data);
            })
          },
        });

        app.factory("EventService", function () {
          var onEventFunc = {};
          /*
          var onEventFunc = {
            token1:[func1,func2,...]
            token2:[func1,func2,...]
          }
          */
          return {
            on: function (type, f) {
              // 检验是否有相关存储
              var callbacks = onEventFunc[type]
              if(callbacks){
                callbacks.push(f)
              }else{
                onEventFunc[type] = [f];
              }
            },
            send: function (type, data) {
              // 取出相应的事件
              var callbacks = onEventFunc[type]
              if (callbacks && callbacks.length > 0) {
                // 遍历触发事件
                callbacks.forEach(callback => {
                  callback(data)
                 })
              }
            },
          };
        });
    </script>
  </body>
</html>
